<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="基本信息">
        <el-form ref="patientForm" :rules="patientrules"  :model="patientForm" label-width="100px" label-position="top">
          <el-row :gutter="10">
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="身份证号" prop="patientIdentityNo">
                  <el-input v-model="patientForm.patientIdentityNo" placeholder="请输入患者身份证号" maxlength="18"/>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <span ref="checkPatient"></span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="患者姓名" prop="patientName">
                  <el-input v-model="patientForm.patientName" placeholder="请输入患者名称" maxlength="10"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者生日" prop="patientBirthday">
                  <el-date-picker clearable
                                  v-model="patientForm.patientBirthday"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择患者生日">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者年龄" prop="patientAge">
                  <el-input v-model="patientForm.patientAge" placeholder="请输入患者年龄"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="患者性别" prop="patientGender">
                  <el-select v-model="patientForm.patientGender" placeholder="请选择患者性别" clearable>
                    <el-option
                      v-for="dict in dict.type.sys_user_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者身高" prop="patientHeight">
                  <el-input v-model="patientForm.patientHeight" placeholder="请输入患者身高" maxlength="3">
                    <i slot="append">cm</i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者体重" prop="patientWeight">
                  <el-input v-model="patientForm.patientWeight" placeholder="请输入患者体重" maxlength="3">
                    <i slot="append">kg</i>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="患者民族" prop="patientFolk">
                  <el-input v-model="patientForm.patientFolk" placeholder="请输入患者民族" maxlength="10"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者职业" prop="patientJob">
                  <el-input v-model="patientForm.patientJob" placeholder="请输入患者职业" maxlength="10"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="婚姻状态" prop="patientMarriage">
                  <el-select v-model="patientForm.patientMarriage" placeholder="请选择患者状态" clearable>
                    <el-option
                      v-for="dict in dict.type.marital_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="患者地址" prop="patientAddress">
                  <el-input v-model="patientForm.patientAddress" placeholder="请输入患者地址" maxlength="30"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="4">
                <el-form-item label="联系方式" prop="patientPhone">
                  <el-input v-model="patientForm.patientPhone" placeholder="请输入联系方式" maxlength="11"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
        </el-form>
      </el-tab-pane>

      <el-tab-pane name="2" label="就诊信息">
        <el-form ref="clinicForm" :rules="clinicrules" :model="clinicForm" label-width="100px" label-position="top">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="患者来源" prop="source">
                <template>
                  <el-radio-group v-model="clinicForm.source">
                    <el-radio :label="0">门诊</el-radio>
                    <el-radio :label="1">住院</el-radio>
                  </el-radio-group>
                </template>
                <!--                  <el-select v-model="form.source" placeholder="请选择患者来源" clearable>-->
                <!--                    <el-option-->
                <!--                      v-for="dict in dict.type.patient_source"-->
                <!--                      :key="dict.value"-->
                <!--                      :label="dict.label"-->
                <!--                      :value="dict.value"-->
                <!--                    />-->
                <!--                  </el-select>-->
                <!--                  <el-input v-model="form.source" placeholder="请输入患者来源"/>-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="病种" prop="disease">
                <el-select v-model="clinicForm.disease" placeholder="请选择患者病种" clearable>
                  <el-option
                    v-for="item in diseaseList"
                    :key="item.id"
                    :label="item.diseaseName"
                    :value="item.diseaseName"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="科室" prop="department">
                <el-select v-model="clinicForm.department" placeholder="请选择患者科室" clearable>
                  <el-option
                    v-for="item in departmentList"
                    :key="item.id"
                    :label="item.departmentName"
                    :value="item.departmentName"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="病区" prop="ward">
                <el-select v-model="clinicForm.ward" placeholder="请选择患者病区" clearable>
                  <el-option
                    v-for="item in wardList"
                    :key="item.id"
                    :label="item.ward"
                    :value="item.ward"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="病床" prop="bedNum">
                <el-input v-model="clinicForm.bedNum" placeholder="请输入病床"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="诊断" prop="preDiagnose">
                <el-input v-model="clinicForm.preDiagnose" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="病情摘要" prop="illnessSummary">
                <el-input v-model="clinicForm.illnessSummary" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="既往史" prop="preHistory">
                <el-input v-model="clinicForm.preHistory" type="textarea" placeholder="请输入既往史"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="家族史" prop="familyHistory">
                <el-input v-model="clinicForm.familyHistory" type="textarea" placeholder="请输入家族史"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <div style="float: right">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-tabs>
  </div>
</template>

<script>
import {listPatient, getPatient, delPatient, addPatient, updatePatient, insertPatient} from "@/api/gaoxin/patient";
import Recorder from "js-audio-recorder";
import {addClinic, listClinicAlive, listClinicbyone, updateClinic} from "@/api/gaoxin/clinic";
import {getUserAll} from "@/api/system/user";
import {listDisease} from "@/api/system/disease";
import {listDepartment} from "@/api/system/department";
import {listWard} from "@/api/system/ward";


export default {
  name: "Patient",
  dicts: ['patient_status','sys_user_sex','marital_status'],
  data() {
    var validateName = (rule, value, callback) => {
      let patientIdentityNo = value;
      let total = 0;
      listPatient({patientIdentityNo: patientIdentityNo}).then(response => {
        total = response.total;
        if (total != 0) {
          callback(new Error('该患者已存在'));
        } else {
          callback();
        }
      })
    };
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      patientForm: {
        patientBirthday: ''
      },
      clinicForm: {},
      //病种列表
      diseaseList: [],
      //科室列表
      departmentList: [],
      //病区列表
      wardList: [],
      // 表单校验
      patientrules: {
        patientName: [
          {required: true, message: "患者名称不能为空", trigger: "blur"},
        ],
        patientIdentityNo: [
          {required: true, message: '身份证不能为空', trigger: "blur"},
          {pattern:/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur'},
        ],
        patientPhone: [
          {required: true, message: "患者联系方式不能为空", trigger: "blur"},
          {pattern:/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/, message: "请输入正确的联系方式(固话加区号)", trigger: "blur"}
        ]
      },
      clinicrules: {
        source: [
          {required: true, message: "患者来源 不能为空", trigger: "blur"},
        ]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        source: null,
        preDiagnose: null,
        manageId: null,
        firstDoctorId: null,
        secondDoctorId: null,
        illnessSummary: null,
        preHistory: null,
        familyHistory: null,
        disease: null,
        department: null,
        ward: null,
        bedNum: null,
        createTime: null,
        outTime: null,
        patientId: null,
        status: null
      },
    };
  },
  created() {
    const path = this.$route.path;
    const patientId = Number(path.split('/').slice(-1));
    this.queryParams.patientId = patientId;
    const query = {patientId: patientId};
    listPatient(query).then(response => {
      this.patientForm = response.rows[0];
    })
    listClinicAlive(query).then(response => {
      console.log("response",response)
      this.clinicForm = response.rows[0];
      this.clinicForm.source = parseInt(this.clinicForm.source);
    })
    this.getDiseaseList();
    this.getDepartmentList();
    this.getWardList();
    // this.getList();
    this.getDicts("marital_status").then(res=>{
      this.marital_status=res.data;
    })
  },
  watch: {
    'patientForm.patientBirthday': {
      handler: function (newVal, oldVal) {
        // console.log(newVal, oldVal);
        if(newVal != '') {
          var birthdays = new Date(newVal.replace(/-/g, "/"));
          var d = new Date();
          var age =
            d.getFullYear() -
            birthdays.getFullYear() -
            (d.getMonth() < birthdays.getMonth() ||
            (d.getMonth() == birthdays.getMonth() &&
              d.getDate() < birthdays.getDate())
              ? 1
              : 0);
          this.patientForm.patientAge = age;
        }

      },
      deep: true
    }
  },
  methods: {
    //查询所有病种
    getDiseaseList() {
      this.loading = true;
      listDisease({pageNum: 1, pageSize: 10, diseaseName: null}).then(response => {
        this.diseaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询所有科室
    getDepartmentList() {
      this.loading = true;
      listDepartment({pageNum: 1, pageSize: 10, departmentName: null}).then(response => {
        this.departmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询所有病区
    getWardList() {
      this.loading = true;
      listWard({pageNum: 1, pageSize: 10, ward: null}).then(response => {
        this.wardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["patientForm"].validate(valid => {
        if(valid){
          this.$refs["clinicForm"].validate(valid => {
            if (valid) {
              updatePatient(this.patientForm).then(response => {
                let patientId = response.patientId;
                this.patientForm.patientId = patientId;
                this.clinicForm.patientId = patientId;
                updateClinic(this.clinicForm).then(response => {
                  this.$modal.msgSuccess("修改成功");
                });
              });
              this.$router.push("/workflow/register/index");
            }
          })
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$tab.closePage();
      this.$router.go(-1);
    },
  }
};
</script>
